import Koa from "koa"
import Router from "koa-router"
import bodyparser from "koa-bodyparser"
import cors from "@koa/cors"
import {Sequelize,Op,DataTypes} from "sequelize"
let app=new Koa()
let router=new Router()
app.use(bodyparser())
app.use(cors())

let sequelize=new Sequelize("demo","root","123456",{
    dialect:"mysql"
})
let User=sequelize.define("user",{
    userName:{
       type: DataTypes.STRING
    },
    userAge:{
        type: DataTypes.INTEGER
    }
})
sequelize.sync({force:true})
router.get("/user",async(ctx)=>{
let id=ctx.params.id
let obj=ctx.request.body
let keyWord=ctx.request.query.keyWord
    let user
if (keyWord) {
     user=await User.findAll({
        where:{
            [Op.or]:{
                userName: {
                    [Op.like]:`%${keyWord}%` 
                },
                userAge: {
                    [Op.like]:`%${keyWord}%` 
                },
            }
        }
     })
    

}else{
     user=await User.findAll()

}
ctx.body={
    data:user,
    msg:"成功",
    code:1000
 }
})
router.get("/user/:id",async(ctx)=>{
    let id=ctx.params.id
let user=await User.findByPk(id)
ctx.body={
    data:user,
    msg:"成功",
    code:1000
 }
})
router.post("/user/:id",async(ctx)=>{
    let obj=ctx.request.body
let user=await User.create(obj)
ctx.body={
    data:user,
    msg:"成功",
    code:1000
 }
})
router.put("/user/:id",async(ctx)=>{
    let id=ctx.params.id
    let obj=ctx.request.body

let user=await User.update(obj,{where:{id}})
ctx.body={
    data:user,
    msg:"成功",
    code:1000
 }
})
router.delete("/user/:id",async(ctx)=>{
    let id=ctx.params.id
let user=await User.destroy({where:{id:id}})
ctx.body={
    data:user,
    msg:"成功",
    code:1000
 }
})
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(5000,function () {
    console.log("http://localhost:5000");
    
})